<?php

namespace App\Http\Controllers\Main;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Category;

class CategoryController extends Controller
{
    # 列表
    public function index(Request $request)
    {
        $this->validate($request, [
            'level' => 'integer|nullable',
            'keyword' => 'string|nullable',
            'parent' => 'integer|nullable',
            'page' => 'integer|nullable',
            'size' => 'integer|nullable',
        ]);

        $level = $request->level;
        $keyword = $request->keyword;
        $parent = $request->parent;
        $limit = ( intval($request->size) < 1 || intval($request->size) > 101 ) ? 10 : intval($request->size);
        $page = ( intval($request->page) < 1 ) ? 1 : intval($request->page);
        $skip = ( $page - 1 )* $limit;

        $builder = Category::where('status', true);
        if ( $level != null )
            $builder = $builder->where('level', $level);
        if ( $parent != null )
            $builder = $builder->where('parent', $parent);
        if ( $keyword != null )
            $builder = $builder->where('name', 'like', "%{$keyword}%");

        $total = $builder->count();
        $cats = $builder->skip($skip)->limit($limit)->get();
        return $this->o(['total'=>$total, 'list'=>$cats]);
    }

    # 详情, 依赖注入Category
    public function show(Request $request, Category $cat)
    {
        // $cat = Category::find($id);
        // $cat->increment('level');
        // $cat->decrement('level');
        return $cat;
    }

    # 新增
    public function store(Request $request)
    {
        $this->validate($request, [
            'level' => 'integer|required',
            'name' => 'string|required|min:2|max:100|unique:categories',
            'status' => 'integer|required',
            'parent' => 'required',
        ]);

        $cat = new Category;
        foreach ( $request->only('level', 'name', 'status', 'parent') as $key=>$value ) {
            $cat->$key = $value;
        }

        $cat->save();
        return $cat;
    }

    # 更新
    public function update(Request $request, Category $cat)
    {
        $this->validate($request, [
            'level' => 'integer|required',
            'name' => 'string|required|min:2|max:100|unique:categories',
            'status' => 'integer|required',
            'parent' => 'required',
        ]);
        foreach ( $request->only('level', 'name', 'status', 'parent') as $key=>$value ) {
            $cat->$key = $value;
        }
        $cat->save();
        return $cat;
    }

    # 删除
    public function destory(Category $cat)
    {
        $cat->delete();
        return $cat;
    }

}
